package com.cruise.game.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.common.constants.CacheConstants;
import com.cruise.game.common.utils.RedisUtils;
import com.cruise.game.mapper.CarouselMapper;
import com.cruise.game.model.entity.Carousel;
import com.cruise.game.model.param.admin.CarouselCreateParam;
import com.cruise.game.model.param.admin.CarouselUpdateParam;
import com.cruise.game.model.vo.admin.CarouselVO;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.service.admin.AdminCarouselService;
import com.cruise.game.service.common.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员轮播图服务实现
 * 
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class AdminCarouselServiceImpl implements AdminCarouselService {

    @Resource
    private CarouselMapper carouselMapper;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private UploadService uploadService;

    @Override
    public PageResult<CarouselVO> getCarouselList(String status, Integer page, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<Carousel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(Carousel::getStatus, status);
        }
        queryWrapper.orderByAsc(Carousel::getSortOrder);
        
        // 分页查询
        IPage<Carousel> carouselPage = carouselMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
        
        // 转换为VO
        List<CarouselVO> carouselVOs = new ArrayList<>();
        for (Carousel carousel : carouselPage.getRecords()) {
            CarouselVO vo = new CarouselVO();
            BeanUtils.copyProperties(carousel, vo);
            carouselVOs.add(vo);
        }
        
        // 构建分页结果
        return PageResult.of(carouselVOs, carouselPage.getTotal(), page, pageSize);
    }

    @Override
    public CarouselVO getCarouselDetail(Long id) {
        // 查询轮播图信息
        Carousel carousel = carouselMapper.selectById(id);
        if (carousel == null) {
            throw new ApiException("轮播图不存在");
        }
        
        // 构建轮播图VO
        CarouselVO carouselVO = new CarouselVO();
        BeanUtils.copyProperties(carousel, carouselVO);
        
        return carouselVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCarousel(CarouselCreateParam param) {
        // 构建轮播图对象
        Carousel carousel = new Carousel();
        BeanUtils.copyProperties(param, carousel);
        
        // 设置排序顺序
        if (carousel.getSortOrder() == null) {
            Integer maxSortOrder = carouselMapper.selectMaxSortOrder();
            carousel.setSortOrder(maxSortOrder != null ? maxSortOrder + 1 : 1);
        }
        
        // 设置状态
        carousel.setStatus("active");
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        carousel.setCreatedAt(now);
        carousel.setUpdatedAt(now);
        
        // 保存轮播图
        carouselMapper.insert(carousel);
        
        // 清除缓存
        redisUtils.del(CacheConstants.CAROUSEL_LIST_CACHE);
        redisUtils.del(CacheConstants.HOME_DATA_CACHE);
        
        return carousel.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCarousel(Long id, CarouselUpdateParam param) {
        // 查询轮播图信息
        Carousel carousel = carouselMapper.selectById(id);
        if (carousel == null) {
            throw new ApiException("轮播图不存在");
        }
        
        // 旧图片URL
        String oldImageUrl = carousel.getImageUrl();
        
        // 更新轮播图
        if (StringUtils.isNotBlank(param.getImageUrl())) {
            carousel.setImageUrl(param.getImageUrl());
        }
        if (StringUtils.isNotBlank(param.getLinkUrl())) {
            carousel.setLinkUrl(param.getLinkUrl());
        }
        if (StringUtils.isNotBlank(param.getTitle())) {
            carousel.setTitle(param.getTitle());
        }
        if (param.getSortOrder() != null) {
            carousel.setSortOrder(param.getSortOrder());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            carousel.setStatus(param.getStatus());
        }
        
        // 设置更新时间
        carousel.setUpdatedAt(LocalDateTime.now());
        
        // 更新轮播图
        boolean success = carouselMapper.updateById(carousel) > 0;
        
        // 清除缓存
        if (success) {
            redisUtils.del(CacheConstants.CAROUSEL_LIST_CACHE);
            redisUtils.del(CacheConstants.HOME_DATA_CACHE);
            
            // 删除旧图片
            if (StringUtils.isNotBlank(oldImageUrl) && StringUtils.isNotBlank(param.getImageUrl()) && !oldImageUrl.equals(param.getImageUrl())) {
                try {
                    uploadService.deleteFile(oldImageUrl);
                } catch (Exception e) {
                    log.error("删除旧轮播图图片失败: {}", e.getMessage(), e);
                }
            }
        }
        
        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCarousel(Long id) {
        // 查询轮播图信息
        Carousel carousel = carouselMapper.selectById(id);
        if (carousel == null) {
            throw new ApiException("轮播图不存在");
        }
        
        // 轮播图图片URL
        String imageUrl = carousel.getImageUrl();
        
        // 删除轮播图
        boolean success = carouselMapper.deleteById(id) > 0;
        
        // 清除缓存
        if (success) {
            redisUtils.del(CacheConstants.CAROUSEL_LIST_CACHE);
            redisUtils.del(CacheConstants.HOME_DATA_CACHE);
            
            // 删除图片
            if (StringUtils.isNotBlank(imageUrl)) {
                try {
                    uploadService.deleteFile(imageUrl);
                } catch (Exception e) {
                    log.error("删除轮播图图片失败: {}", e.getMessage(), e);
                }
            }
        }
        
        return success;
    }
}
